<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Create_user extends CI_Controller {
    public function index()
    {
        $this->editUser(-1);
    }
    
    public function editUser($user_id){
        $this->load->model('basetypes');
        $this->load->model('users');
        
        $basetypes = $this->basetypes->getAll();
        $user = $this->users->getByID($user_id);
        
        if ($user != null){
            $title = "Update User";
            $subtitle = $user->user_title;
            $save_text = "Update User";
        }
        else{
            $title = "Create User";
            $subtitle = "";
            $save_text = "Create User";
        }
        $requirements = $this->users->getBasetypes($user_id);
        
        $password = generate_password(6,0);
        
        $data['title'] = $title;
        $data['data'] = array (
            "subtitle" => $subtitle,
            "basetypes" => $basetypes,
            "requirements" => $requirements,
            "user" => $user,
            "save_text" => $save_text,
            "password" => $password
        );
        $data['js'] = array('create_user.js');
        $data['view'] = "settings/view_create_user";
        $this->load->view('view_template',$data);
    }
    
    public function postUser(){
        extract($this->ajax->post("user_id","username","email","name","password", "change", "edit"));
        $requirements = $this->input->post('requirements');
        $this->load->model("users");
        $this->load->helper('email');
        //validate data        
        $error = array();
                
        if ($this->checkLogin($user_id, $username)){
            $error['login'] = "Username must be unique";
        }
          
        if ($this->checkEmail($user_id, $email)){
            $error['email'] = "Email must be unique"; 
        }
        
        if (!valid_email($email)){
            $error['email'] = 'Email address is invalid';
        }
        
        if (count($error) > 0){
            echo json_encode($error);
            return;
        }
        
        $oldemail = $email;
        if ($user_id > 0){
            try{
                $olduser = $this->users->getByID($user_id);
                $oldemail = $olduser->user_email;
                $username = $olduser->user_login;
            }
            catch(Exception $e){}
        }
        
        if ($change == 0){
            if ($this->users->insertUser($user_id, $username, $email, $name, $requirements, $edit, encrypt_password($password)) === FALSE){
                $this->session->set_flashdata('user_response',"There was an error processing your request.");
                echo json_encode("server");
                return;
            }
        }
        else{
            if ($this->users->insertUser($user_id, $username, $email, $name, $requirements, $edit) === FALSE){
                $this->session->set_flashdata('user_response',"There was an error processing your request.");
                echo json_encode("server");
                return;
            }
        }
        $this->load->helper('email');
        //Falls through for both if good
        if ($user_id == -1){
            $this->session->set_flashdata('user_response',"User '$username' succesfully created.");
            echo json_encode("good");
            send_email_advanced($email, "Hi $name, Welcome to RMPlanner", 
                    "Hello $name,\r\n".
                    "Your user account '$username' has been successfully created.\r\n".
                    "Your password is:\r\n\r\n$password\r\n\r\n".
                    "Remember to change this once you log in\r\n\r\n".
                    "Thanks for joining,\r\n from all the team at RMPlanner"
                    );
        }
        else{
            $this->session->set_flashdata('user_response',"User '$username' succesfully updated.");
            echo json_encode("update");
            if ($change != 0){
            send_email_advanced($email, "RMPlanner: Your account has been updated", 
                    "Hello,\r\n".
                    "Your user account '$username' has had it's password reset.\r\n".
                    "Your password is now:\r\n\r\n$password\r\n\r\n".
                    "Remember to change this once you log in\r\n\r\n".
                    "Thanks,\r\n from all the team at RMPlanner"
                    );
            }
            if ($oldemail != $email){
                send_email_advanced($oldemail, "RMPlanner: Your email address has changed", 
                    "Hello $name,\r\n".
                    "Your email address for account $username has changed to '$email'\r\n".
                    "If you believe this is a mistake, please contact the kitchen staff.\r\n\r\n".
                    "Thanks,\r\n from all the team at RMPlanner"
                    );
            }
        }
    }
    
    public function checkLogin($user_id = null, $user_login = null){
        $echo = false;
        //We have an ajax request
        if ($user_id == null || $user_login == null){
            extract($this->ajax->post('user_login','user_id'));
            $echo = true;
        }
        
        $this->load->model('users');
        
        $user = $this->users->getByLogin($user_login);

        $returnString = "good";
        $returnValue = false;
        
        if ($user != null){
            if ($user_login == $user->user_login){
                if ($user_id != $user->user_id){
                    $returnString = "used";
                    $returnValue = true;
                }
            }
        }
        if ($echo){
            echo $returnString;
        }
        else{
            return $returnValue;
        }
    }
    
    public function checkEmail($user_id = null, $user_email = null){
        $echo = false;
        
        //We have an ajax request
        if ($user_id == null || $user_email == null){
            extract($this->ajax->post('user_email','user_id'));
            $this->load->model('users');
            $echo = true;
        }
        
        $user = $this->users->getByEmail($user_email);

        $returnString = "good";
        $returnValue = false;
        
        if ($user != null){
            if ($user_email == $user->user_email){
                if ($user_id != $user->user_id){
                    $returnString = "used";
                    $returnValue = true;
                }
            }
        }
        if ($echo){
            echo $returnString;
        }
        else{
            return $returnValue;
        }
    }
}

